﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
//using System.Data.Entity;

namespace Order
{
    [DataContract]
    public class Order : ICloneable
    {
        [DataMember]
        public string OrderID { get; set; }
        [DataMember]
        public Customer TheCustomer { get; set; }
        [DataMember]
        public DateTime OrderTime { get; set; }
        [DataMember]
        public double Total { get; private set; }
        [DataMember]
        public Address ShippingAddress { get; set; }
        [DataMember]
        public List<OrderDetail> OrderDetails { get; set; }
        public Order()
        {
            OrderTime = DateTime.Now;
            TheCustomer = new Customer();
            ShippingAddress = new Address();
            OrderDetails = new();
        }
        public override bool Equals(object obj)
        {
            if (obj is not Order o) return false;
            return o.OrderID == OrderID;
        }
        public override string ToString()
        {
            //if (OrderID == null) throw new NullReferenceException();
            StringBuilder builder = new();
            builder.Append($"Order Id: {OrderID}\nCustomer: {TheCustomer}\nOrder Time: {OrderTime}\n");
            builder.Append($"Total: {Total}\nShipping Address: {ShippingAddress}");
            if (OrderDetails != null)
            {
                foreach (var item in OrderDetails)
                {
                    builder.Append($"\n{item}");
                }
            }
            return builder.ToString();
        }

        public override int GetHashCode()
        {
            return OrderID.GetHashCode();
        }
        public void ComputeTotal()
        {
            Total = 0;
            if (OrderDetails == null) return;
            foreach (var d in OrderDetails)
            {
                Total += (d.Commodity?.Price ?? 0) * d.Amount;
            }
        }

        public object Clone()
        {
            var order = new Order()
            {
                OrderID = OrderID,
                ShippingAddress = ShippingAddress.Clone() as Address,
                OrderTime = OrderTime,
                TheCustomer = TheCustomer.Clone() as Customer,
                Total = Total
            };
            foreach (var detail in OrderDetails)
            {
                order.OrderDetails.Add(detail.Clone() as OrderDetail);
            }
            return order;
        }
    }
}
